package com.example.teaching_server.controller;

import com.example.teaching_server.common.ApiResponse;
import com.example.teaching_server.dto.UserCheckinRequest;
import com.example.teaching_server.dto.CheckinResultDTO;
import com.example.teaching_server.entity.ActivityCheckinEntity;
import com.example.teaching_server.service.UserCheckinService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/user-activities")
@RequiredArgsConstructor
@Tag(name = "用户打卡管理", description = "用户活动打卡相关接口")
public class UserCheckinController {
    private final UserCheckinService userCheckinService;

    /**
     * 活动打卡
     */
    @PostMapping("/checkin")
    @Operation(summary = "活动打卡", description = "用户对指定活动进行打卡")
    public ApiResponse<CheckinResultDTO> checkin(
            @Parameter(description = "活动ID") @RequestParam Long activityId,
            @RequestBody UserCheckinRequest request) {

        log.info("收到打卡请求: activityId={}, userId={}, descriptionLength={}, imageCount={}",
                activityId, request.getUserId(),
                request.getDescription() != null ? request.getDescription().length() : 0,
                request.getImageUrls() != null ? request.getImageUrls().size() : 0);

        try {
            ActivityCheckinEntity result = userCheckinService.checkin(activityId, request);
            CheckinResultDTO dto = CheckinResultDTO.fromEntity(result);
            return ApiResponse.success("打卡成功", dto);
        } catch (Exception e) {
            log.error("打卡失败: activityId={}, userId={}", activityId, request.getUserId(), e);
            return ApiResponse.fail("打卡失败: " + e.getMessage());
        }
    }

    /**
     * 批量打卡
     */
    @PostMapping("/batch-checkin")
    @Operation(summary = "批量打卡", description = "用户对多个活动进行批量打卡")
    public ApiResponse<List<CheckinResultDTO>> batchCheckin(
            @RequestBody BatchCheckinRequest request) {

        log.info("收到批量打卡请求: userId={}, activityCount={}",
                request.getUserId(),
                request.getActivityIds() != null ? request.getActivityIds().size() : 0);

        try {
            List<CheckinResultDTO> results = new ArrayList<>();
            int successCount = 0;
            int failCount = 0;

            for (Long activityId : request.getActivityIds()) {
                try {
                    UserCheckinRequest checkinRequest = new UserCheckinRequest();
                    checkinRequest.setUserId(request.getUserId());
                    checkinRequest.setDescription(request.getDescription());
                    checkinRequest.setImageUrls(request.getImageUrls());

                    ActivityCheckinEntity result = userCheckinService.checkin(activityId, checkinRequest);
                    results.add(CheckinResultDTO.fromEntity(result));
                    successCount++;
                } catch (Exception e) {
                    log.warn("单个活动打卡失败: activityId={}, userId={}, error={}",
                            activityId, request.getUserId(), e.getMessage());
                    failCount++;
                    // 单个失败不影响其他活动打卡
                }
            }

            log.info("批量打卡完成: userId={}, 成功{}个, 失败{}个",
                    request.getUserId(), successCount, failCount);
            return ApiResponse.success("批量打卡完成", results);
        } catch (Exception e) {
            log.error("批量打卡异常: userId={}", request.getUserId(), e);
            return ApiResponse.fail("批量打卡失败: " + e.getMessage());
        }
    }

    /**
     * 获取用户打卡记录
     */
    @GetMapping("/checkin-records")
    @Operation(summary = "获取打卡记录", description = "获取用户的打卡记录")
    public ApiResponse<List<CheckinResultDTO>> getCheckinRecords(
            @Parameter(description = "用户ID") @RequestParam Long userId,
            @Parameter(description = "活动ID") @RequestParam(required = false) Long activityId,
            @Parameter(description = "打卡日期") @RequestParam(required = false)
            @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate checkDate) {

        log.info("开始获取打卡记录: userId={}, activityId={}, checkDate={}",
                userId, activityId, checkDate);

        try {
            // 这里需要实现获取打卡记录的逻辑
            // 暂时返回空列表，需要根据实际情况实现
            List<CheckinResultDTO> records = new ArrayList<>();
            log.info("成功获取{}条打卡记录", records.size());
            return ApiResponse.success("打卡记录获取成功", records);
        } catch (Exception e) {
            log.error("获取打卡记录失败: userId={}", userId, e);
            return ApiResponse.fail("获取打卡记录失败: " + e.getMessage());
        }
    }

    /**
     * 路径参数打卡接口（兼容性保留）
     */
    @PostMapping("/{activityId}/checkin")
    @Operation(summary = "活动打卡(路径参数)", description = "使用路径参数进行活动打卡")
    public ApiResponse<CheckinResultDTO> checkinWithPath(
            @Parameter(description = "活动ID") @PathVariable Long activityId,
            @RequestBody UserCheckinRequest request) {

        log.info("收到路径参数打卡请求: activityId={}, userId={}", activityId, request.getUserId());

        // 直接调用新的查询参数接口
        return checkin(activityId, request);
    }

    /**
     * 批量打卡请求DTO
     */
    @Setter
    @Getter
    public static class BatchCheckinRequest {
        private Long userId;
        private List<Long> activityIds;
        private String description;
        private List<String> imageUrls;

    }
}
